package com.sihan.framework.etm.service.impl;

import com.framework.constant.WebConstants;
import com.sihan.framework.etm.entity.User;
import com.sihan.framework.etm.service.SessionService;
import com.sihan.framework.etm.vo.SessionVO;

import java.util.*;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SessionServiceImpl implements SessionService {

  @Autowired
  private SessionDAO sessionDAO;

  @Override
  public List<SessionVO> selectSessions() {
    List<Session> activeSessions = new ArrayList<>(sessionDAO.getActiveSessions());
    Map<String, SessionVO> map = new HashMap<>();
    List<SessionVO> sessions = new ArrayList<>();
    for (Session session : activeSessions) {
      if(session.getId() != null && session.getAttribute(WebConstants.CURRENT_USER) != null) {

        SessionVO sessionVO = new SessionVO();
        sessionVO.setId((String) session.getId());
        sessionVO.setCreateTime(session.getStartTimestamp());
        sessionVO.setLastAccessTime(session.getLastAccessTime());
        sessionVO.setHost(session.getHost());
        sessionVO.setTimeOut(session.getTimeout() / 1000);
        sessionVO.setUsername(usernameFromSession(session));
        //后面创建的覆盖前面的
        if(map.containsKey(sessionVO.getUsername())) {
          if(map.get(sessionVO.getUsername()).getCreateTime().before(sessionVO.getCreateTime())) {
            map.put(sessionVO.getUsername(), sessionVO);
          }
        } else {
          map.put(sessionVO.getUsername(), sessionVO);
        }
      }
    }

    if(map.size() > 0) {
      Set<Map.Entry<String, SessionVO>> entry = map.entrySet();
      for(Map.Entry<String, SessionVO> en : entry) {
        sessions.add(en.getValue());
      }
    }
    return sessions;
  }

  @Override
  public boolean isExpires(String sessionId) {
    Collection<Session> activeSessions = sessionDAO.getActiveSessions();
    for (Session s:activeSessions) {
          if(s.getId().equals(sessionId)){
            return true;
          }
    }
    return false;
  }

  private String usernameFromSession(Session session) {
    PrincipalCollection principalCollection = (PrincipalCollection)
        session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
    if (principalCollection != null) {
      return (String) principalCollection.getPrimaryPrincipal();
    }
    return null;
  }

  @Override
  public boolean delete(String sessionId) {
    Session session = sessionDAO.readSession(sessionId);
    sessionDAO.delete(session);
    return true;
  }


}
